package com.ting.test.util.ftp;

import com.u51pay.antispoofing.config.FtpProperties;
import com.u51pay.antispoofing.utils.DateUtils;
import com.u51pay.antispoofing.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.Date;

public class FtpUtil {
	private static String separator=File.separator;
	
	private static Logger logger=Logger.getLogger(FtpUtil.class);
	
	private static FTPClient ftp;
	
	/**
	 * 获取ftp连接
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public static boolean connectFtp(FtpProperties f) throws Exception{
		boolean flag = false;
		try {
			ftp = new FTPClient();
			int reply;
			if (f.getPort() == null) {
				ftp.connect(f.getIp(), 21);
			} else {
				ftp.connect(f.getIp(), f.getPort());
			}
			ftp.login(f.getUserName(), f.getPassWord());
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return flag;
			}
			flag = true;
		}catch (Exception e){
			flag=false;
		}
	    return flag;
	}
	
	/**
	 * 关闭ftp连接
	 */
	public static void closeFtp(){
		if (ftp!=null && ftp.isConnected()) {
			try {
				ftp.logout();
				ftp.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * ftp上传文件
	 * @param f
	 * @throws Exception
	 */
	public static void upload(File f) throws Exception{
		if (f.isDirectory()) {
			ftp.makeDirectory(f.getName());
			ftp.changeWorkingDirectory(f.getName());
			String[] files=f.list();
			for(String fstr : files){
				File file1=new File(f.getPath()+separator+fstr);
				if (file1.isDirectory()) {
					upload(file1);
					ftp.changeToParentDirectory();
				}else{
					File file2=new File(f.getPath()+separator+fstr);
					FileInputStream input=new FileInputStream(file2);
					ftp.storeFile(file2.getName(),input);
					input.close();
				}
			}
		}else{
			File file2=new File(f.getPath());
			FileInputStream input=new FileInputStream(file2);
			ftp.storeFile(file2.getName(),input);
			input.close();
		}
	}
	
	/**
	 * 下载链接配置
	 * @param localBaseDir 本地目录
	 * @param remoteBaseDir 远程目录
	 * @throws Exception
	 */
	public static void startDownFiles(String localBaseDir,String remoteBaseDir ) throws Exception{
	        try {
	            FTPFile[] files;
	            boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);
	            if (changedir) { 
	                ftp.setControlEncoding("GBK"); 
	                files = ftp.listFiles(); 
	                for (int i = 0; i < files.length; i++) {
                       String fileName= files[i].getName();
                        String DateStr=fileName.substring(fileName.lastIndexOf(StringUtil.UNDERLINE));
                        if(StringUtils.isEmpty(DateStr)){
                            continue;
                        }
                        Date fileDate= DateUtils.parseFromYYYY_MM_DD_HH_MM_SS(DateStr);
                        Date nowDate=new Date();
                        Date beforeDate5Min= DateUtils.getDateByMinute(nowDate,-5);
                        if(!fileDate.after(beforeDate5Min)){
								continue;
						}

	                    try{ 
	                        downloadFile(fileName, localBaseDir);
	                    }catch(Exception e){ 
	                    	logger.error(e); 
	                    	logger.error("<"+files[i].getName()+">下载失败"); 
	                    } 
	                } 
	            } 
	        } catch (Exception e) { 
	        	logger.error(e); 
	        	logger.error("下载过程中出现异常"); 
	        } 
	}

	/**
	 * 下载链接配置
	 * @param localBaseDir 本地目录
	 * @param remoteBaseDir 远程目录
	 * @throws Exception
	 */
	public static void startDownFile(String localBaseDir,String remoteBaseDir,String fileName ) throws Exception{
		try {
			boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);
			if (changedir) {
				ftp.setControlEncoding("GBK");
					try{
						downloadFile(fileName, localBaseDir);
					}catch(Exception e){
						logger.error(e);
						logger.error("<"+fileName+">下载失败");
					 }
			}
		} catch (Exception e) {
			logger.error(e);
			logger.error("下载过程中出现异常");
		}
	}
	
	
	/** 
     * 
     * 下载FTP文件 
     * 当你需要下载FTP文件的时候，调用此方法 
     * 根据<b>获取的文件名，本地地址，远程地址</b>进行下载 
     * 
     * @param ftpFile 
     * @param relativeLocalPath 
     * @param relativeRemotePath 
     */ 
    private  static void downloadFiles(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) {
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) { 
                OutputStream outputStream = null; 
                try { 
                    File locaFile= new File(relativeLocalPath+separator+ftpFile.getName());
                    //判断文件是否存在，存在则返回 
                    if(locaFile.exists()){ 
                        return; 
                    }else{ 
                        outputStream = new FileOutputStream(relativeLocalPath+separator+ ftpFile.getName());
                        ftp.retrieveFile(ftpFile.getName(), outputStream); 
                        outputStream.flush(); 
                        outputStream.close(); 
                    } 
                } catch (Exception e) { 
                    logger.error(e);
                } finally { 
                    try { 
                        if (outputStream != null){ 
                            outputStream.close(); 
                        }
                    } catch (IOException e) { 
                       logger.error("输出文件流异常"); 
                    } 
                } 
            } 
        } else { 
            String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
            String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); 
            File fl = new File(newlocalRelatePath); 
            if (!fl.exists()) { 
                fl.mkdirs(); 
            } 
            try { 
                newlocalRelatePath = newlocalRelatePath + separator;
                newRemote = newRemote + separator;
                String currentWorkDir = ftpFile.getName().toString(); 
                boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); 
                if (changedir) { 
                    FTPFile[] files = null; 
                    files = ftp.listFiles(); 
                    for (int i = 0; i < files.length; i++) { 
                        downloadFiles(files[i], newlocalRelatePath, newRemote);
                    } 
                } 
                if (changedir){
                	ftp.changeToParentDirectory(); 
                } 
            } catch (Exception e) { 
                logger.error(e);
            } 
        } 
    }


	/**
	 *
	 * 下载单个文件
	 * 当你需要下载FTP文件的时候，调用此方法
	 * 根据<b>获取的文件名，本地地址，远程地址</b>进行下载
	 *
	 * @param fileName
	 * @param relativeLocalPath
	 */
	private  static void downloadFile(String fileName , String relativeLocalPath) {
			if (fileName.indexOf("?") == -1) {
				OutputStream outputStream = null;
				try {
					File locaFile= new File(relativeLocalPath+separator+fileName);
					//判断文件是否存在，存在则返回
					if(locaFile.exists()){
						return;
					}else{
						outputStream = new FileOutputStream(relativeLocalPath+separator+ fileName);
						ftp.retrieveFile(fileName, outputStream);
						outputStream.flush();
						outputStream.close();
					}
				} catch (Exception e) {
					logger.error(e);
				} finally {
					try {
						if (outputStream != null){
							outputStream.close();
						}
					} catch (IOException e) {
						logger.error("输出文件流异常");
					}
				}
			}
	}


}
